package com.tea.app.moudles.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tea.app.moudles.entity.GoodsCollection;
import com.tea.app.moudles.mapper.GoodsCollectionMapper;
import com.tea.app.moudles.service.GoodsCollectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GoodsCollectionServiceImpl implements GoodsCollectionService {
    
    @Autowired
    private GoodsCollectionMapper collectionMapper;

    @Override
    public void addCollection(String wxOpenid, Long goodsId) {
        // 检查是否已收藏
        QueryWrapper<GoodsCollection> wrapper = new QueryWrapper<>();
        wrapper.eq("wx_openid", wxOpenid).eq("goods_id", goodsId);
        if(collectionMapper.selectCount(wrapper) == 0) {
            GoodsCollection collection = new GoodsCollection();
            collection.setWxOpenid(wxOpenid);
            collection.setGoodsId(goodsId);
            collection.setCreateTime(new Date());
            collectionMapper.insert(collection);
        }
    }

    @Override
    public void removeCollection(String wxOpenid, Long goodsId) {
        QueryWrapper<GoodsCollection> wrapper = new QueryWrapper<>();
        wrapper.eq("wx_openid", wxOpenid).eq("goods_id", goodsId);
        collectionMapper.delete(wrapper);
    }

    @Override
    public List<Long> getUserCollectionGoodsIds(String wxOpenid) {
        QueryWrapper<GoodsCollection> wrapper = new QueryWrapper<>();
        wrapper.eq("wx_openid", wxOpenid);
        return collectionMapper.selectList(wrapper)
                .stream()
                .map(GoodsCollection::getGoodsId)
                .collect(Collectors.toList());
    }

    @Override
    public List<GoodsCollection> getUserCollections(String wxOpenid) {
        QueryWrapper<GoodsCollection> wrapper = new QueryWrapper<>();
        wrapper.eq("wx_openid", wxOpenid);
        return collectionMapper.selectList(wrapper);
    }
}